<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>响应式</title>
    <!-- <script src="./vue.global.js"></script> -->
    <!--引入vue2开发版本的vue核心包-->
    <script src="https://cdn.jsdelivr.net/npm/vue@2.7.10/dist/vue.js"></script>
</head>

<!--
computed计算属性和methods的区别
computed计算属性具备缓存，多次调用只执行一次，下次读取直接读取缓存，性能高
computed计算属性用于计算出一个结果，methods用于处理一段逻辑
-->
<style>

</style>

<body>
    <div id="app">
        <p>购物车<span>{{sum}}</span></p>
        <p>购物车<span>{{sum}}</span></p>
        <p>购物车<span>{{sum}}</span></p>

        <table>
            <thead>
                <tr>
                    <td>名字</td>
                    <td>数量</td>
                    <td>单价</td>
                </tr>
            </thead>
            <tbody>
                <tr v-for="(item,index) in list" :key="item.id">
                    <td>{{item.name}}</td>
                    <td>{{item.num}}</td>
                    <td>{{item.price}}</td>
                </tr>
            </tbody>
        </table>
        礼物总数：{{sum}}
        总价：{{ sumPrice() }}
        总价：{{ sumPrice() }}
        总价：{{ sumPrice() }}
        总价：{{ sumPrice() }}
    </div>

    <script>
        const app = new Vue({
            el: '#app',
            data: {
                list: [{ name: '篮球', num: 1, price: 20 }, { name: '足球', num: 2, price: 30 }, { name: '排球', num: 5, price: 20 }]
            },
            methods: {
                sumPrice() {
                    console.log("方法运行了")
                    let sumPrice = this.list.reduce((sum, item) => sum + item.num * item.price, 0)
                    return sumPrice
                }
            },
            computed: {
                sum() {
                    // let su = 0
                    // this.list.forEach(el => su += el.num);
                    // return su

                    console.log("computed计算属性执行了，用来测试执行次数，验证缓存")

                    // 遍历数组求和使用reduce方法
                    let total = this.list.reduce((sum, item) => sum + item.num, 0)
                    return total
                }
            }
        })
    </script>

</body>

</html>